<?php

namespace app\api\service;

use app\common\model\Performance;
use app\common\model\User;

class PerformanceService
{
    private static $instance;

    protected $ars = [
        '0' => '无',
        '1' => '销售经理',
        '2' => '销售总监',
        '3' => '董事',
    ];
    public static function getInstance() {
        if (!(self::$instance instanceof self)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function performance()
    {
        try {
            $allUsers = $this->getUsersWithNonZeroOrderAmount();

            foreach ($allUsers as $user) {
                $totalPerformance = $this->calculatePerformanceExcludingMax($user->id);
                $rank = $this->getRankForPerformance($totalPerformance);

                if ($user->rank_id < $rank) {
                    if ($rank == 3) {   //  董事特殊处理
                        $count = User::where('rank_id', 2)->where('direct_push', $user->id)->count();
                        if ($count < 3) {   //  要求要有三个总监
                            $rank = $user->rank_id;
                        }
                    }
                    User::update(['rank_id' => $rank], ['id' => $user->id]);
                }
            }
        } catch (\Exception $e) {
            // 记录异常日志
            error_log("performanceReward Error: " . $e->getMessage());
        }

    }

    public function performanceReward()
    {
        $this->Reward(1, 0.05, '销售经理绩差奖励');
        $this->Reward(2, 0.03, '销售总监绩差奖励');
        $this->Reward(3, 0.02, '董事绩差奖励');
    }

    public function Reward($rankId, $percentage, $memoSuffix)
    {
        try {
            $time = date('Y-m-d', time());
            $allUsers = User::where('rank_id', '>=', $rankId)->field('id,money,score')->select();

            $allMoney = Performance::get(1);
            if (empty($allMoney['performance']) || $allMoney['performance'] <= 0) {
                throw new \Exception("No available performance amount.");
            }

            $allNum = count($allUsers);
            if ($allNum === 0) {
                return;
            }

            $rewardAmount = bcdiv(bcmul($allMoney['performance'], $percentage, 2), $allNum, 2);

            foreach ($allUsers as $user) {
                self::money($rewardAmount, $user['id'], $time . $memoSuffix);
                self::score($rewardAmount, $user['id'], $time . $memoSuffix);
            }
        } catch (\Exception $e) {
            error_log("Reward Error: " . $e->getMessage());
        }
    }

    public static function money($money, $user_id, $memo, $type = '', $ids = '')
    {
        try {
            $user = model('app\common\model\User')->get($user_id);
            if (!$user || $money == 0) {
                return ['code' => 500, 'msg' => '变更金额失败'];
            }

            $before = $user->money;
            $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;

            $user->save(['money' => $after]);

            $row = model('app\common\model\MoneyLog')->create([
                'user_id' => $user_id,
                'money' => $money,
                'before' => $before,
                'after' => $after,
                'memo' => $memo,
                'type' => $type,
                'service_ids' => $ids,
            ]);

            return $row;
        } catch (\Exception $e) {
            error_log("Money Change Error: " . $e->getMessage());
            return ['code' => 500, 'msg' => '变更金额失败'];
        }
    }

    public static function score($money, $user_id, $memo)
    {
        try {
            $user = model('app\common\model\User')->get($user_id);
            if (!$user || $money == 0) {
                return ['code' => 500, 'msg' => '变更积分失败'];
            }

            $before = $user->score;
            $after = function_exists('bcadd') ? bcadd($user->score, $money, 2) : $user->score + $money;

            $user->save(['score' => $after]);

            $row = model('app\common\model\ScoreLog')->create([
                'user_id' => $user_id,
                'score' => $money,
                'before' => $before,
                'after' => $after,
                'memo' => $memo,
            ]);

            return $row;
        } catch (\Exception $e) {
            error_log("Score Change Error: " . $e->getMessage());
            return ['code' => 500, 'msg' => '变更积分失败'];
        }
    }

    public function getUsersWithNonZeroOrderAmount()
    {
        return User::where('product_orders', '>', 199)->field('id,rank_id,product_orders')->select();
    }

    private function calculatePerformanceExcludingMax($uid)
    {
        try {
            $subordinates = User::where('direct_push', $uid)->field('product_orders')->select();
            $performanceValues = array_column($subordinates, 'product_orders');

            if (empty($performanceValues)) {
                return 0;
            }

            rsort($performanceValues);
            array_shift($performanceValues);

            return array_sum($performanceValues);
        } catch (\Exception $e) {
            error_log("Calculate Performance Error: " . $e->getMessage());
            return 0;
        }
    }

    private function getRankForPerformance($totalPerformance)
    {
        $thresholds = [
            15000000 => '3',
            500000 => '2',
            130000 => '1',
            0 => '0',
        ];

        foreach ($thresholds as $threshold => $rankId) {
            if ($totalPerformance >= $threshold) {
                return $rankId;
            }
        }

        return '0';
    }
}
